package com.erpanderp.wam.util;
import java.io.IOException;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.List;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.erpanderp.wam.usm.model.entity.user.WAMUser;
import com.erpanderp.wam.usm.model.service.user.WAMUserDAO;

public class WAMPasswordUtil {

	private static final String ALGO = "AES";
	private static final byte[] keyValue = new byte[] {'S', 'e', 'c', 'u', 'r', 'e', 'd', 'W', 'A', 'M', 'S', 'e', 'c', 'r', 'e', 't'};

	public static String encrypt(String data) throws Exception {
		Key key = generateKey();
		Cipher c = Cipher.getInstance(ALGO);
		c.init(Cipher.ENCRYPT_MODE, key);
		byte[] encVal = c.doFinal(data.getBytes());
		String encryptedValue = new BASE64Encoder().encode(encVal);
		return encryptedValue;
	}

	public static String decrypt(String encryptedData) throws Exception {
		Key key = generateKey();
		Cipher c = Cipher.getInstance(ALGO);
		c.init(Cipher.DECRYPT_MODE, key);
		byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
		byte[] decValue = c.doFinal(decordedValue);
		String decryptedValue = new String(decValue);
		return decryptedValue;
	}
	
	private static Key generateKey() throws Exception {
        Key key = new SecretKeySpec(keyValue, ALGO);
        return key;
	}

	public static void main(String a[]) throws Exception {
		String encrypted = encrypt("Daia1234");

		System.out.println(encrypted);
		System.out.println(decrypt(encrypted));

		// Code for encrypting all passwords

		WAMUserDAO wamUserDAO = new WAMUserDAO();
		List<WAMUser> wamUsers = wamUserDAO.getWAMUsers();
		
		//Run these code to encrypt
		/*for (WAMUser wamUser : wamUsers) {
			wamUser.setPassword(WAMPasswordUtil.encrypt(wamUser.getPassword()));
		}
		wamUserDAO.updateWAMUsers(wamUsers);*/

		//Run these to view password 
		for (WAMUser wamUser : wamUsers) {
			// wamUser.setPassword(WAMPasswordUtil.encrypt(wamUser.getPassword()));
			System.out.println(wamUser.getEmployeeCode());
			System.out.println(wamUser.getPassword());
			System.out.println(decrypt(wamUser.getPassword()));
		}

	}

}